package org.hhchat.leetcode.string;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created this one by HMH on 2017/11/26.
 */
public class code43_medium {

    static class Solution {
        public String multiply(String num1, String num2) {
            int[] num1Arr = new int[num1.length()];
            int[] num2Arr = new int[num2.length()];
            for (int i = 0; i < num1.length(); i++) {
                num1Arr[i] = num1.charAt(i) - '0';
            }
            for(int i = 0 ; i < num2.length(); i++) {
                num2Arr[i] = num2.charAt(i) - '0';
            }
            List<int[]> tempList = new ArrayList<>();
            for (int j = num2Arr.length - 1; j >= 0; j--) {
                    tempList.add(mupltiply(num1Arr, num2Arr[j], tempList.size()));
            }

            int[] result = tempList.stream().reduce(this::add).get();
            StringBuilder sb = new StringBuilder();
            boolean isFront = true;
            for (int aResult : result) {
                if(aResult==0 && isFront){
                    continue;
                }
                isFront = false;
                sb.append(aResult);
            }
            if (sb.length() == 0) {
                sb.append(0);
            }
            return sb.toString();
        }

        public int[] add(int[] num1, int[] num2) {
            Stack<Integer> result = new Stack<>();
            int length1 = num1.length-1;
            int length2 = num2.length-1;
            int c = 0;
            while (length1 >= 0 || length2 >= 0) {
                int a = length1 >= 0 ? num1[length1--] : 0;
                int b = length2 >= 0 ? num2[length2--] : 0;
                int temp = a + b + c;
                result.push(temp % 10);
                c = temp / 10;
            }
            if (c != 0) {
                result.push(c);
            }
            int[] arr = new int[result.size()];
            int count = 0;
            while (!result.isEmpty()) {
                arr[count++] = result.pop();
            }
            return arr;
        }

        public int[]  mupltiply(int[] num1, int num2, int zeroLength) {
            Stack<Integer> result = new Stack<>();
            int c = 0;
            while (zeroLength-->0) {
                result.push(0);
            }
            for (int i = num1.length - 1; i >= 0; i--) {
                int temp = num1[i] * num2 + c;
                c = temp / 10;
                result.push(temp % 10);
            }
            if (c != 0) {
                result.push(c);
            }
            int[] arr = new int[result.size()];
            int count = 0;
            while (!result.isEmpty()) {
                arr[count++] = result.pop();
            }
            return arr;
        }
    }

    public static void main(String[] args){
        Solution solution = new Solution();

        System.out.println((solution.multiply("1234","4321")));
    }

}

